<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/2
 * Time: 21:11
 */

namespace Home\Controller;

use Common\Controller\HomeController;
use Common\Model\GoodsListModel;
use Common\Model\GoodsModel;
use Common\Model\TypeAttrModel;
use Org\Util\Cart;

class ContentController extends HomeController
{
	/**
	 * 首页 内容页面
	 */
	public function index(){
		//分配公共头部数据
		$conf = ['js'=>['list'],
			'css'=>['index']
		];
		$this->assign('conf',$conf);

//		dd(I('get.'));
		$gid = I('get.gid');
		//获取商品及详细信息
		$data = (new GoodsModel())->alias('g')->join("ccshop_detail d on g.gid=d.gid")->where("g.gid={$gid}")->find();
		//处理规格数据
		$specData = (new TypeAttrModel())->alias('ta')->join("ccshop_goods_attr ga on ta.taid=ga.taid")->where("ga.gid={$gid} and ta.class=1")->select();
		$temp = [];
		foreach($specData as $k=>$v){
			$temp[$v['taname']][] =$v;
		}
//		dd($specData);
//		dd($data);
//		dd($temp);
		$this->assign('data',$data);
		$this->assign('temp',$temp);
		$this->display();
	}

	/**
	 * 异步获取货存
	 */
	public function ajaxGetTotal(){
		if (IS_AJAX){
			$data['gid'] = I('post.gid');
			$data['combine'] = rtrim(I('post.combine'),',');
			//根据参数在goodslist表中查询
			$data = (new GoodsListModel())->where("gid={$data['gid']} AND combine='{$data['combine']}'")->find();
			//如果不存在该样式 返回0
			if (!$data){
				echo json_encode(['valid'=>0,'message'=>'']);
				exit;
			}
			//能查询到数据，但是货存为0
			if($data['inventory']==0){
				echo json_encode(['valid'=>0,'message'=>'']);exit;
			}

			echo json_encode(['valid'=>1,'message'=>'','inventory'=>$data['inventory']]);
			exit;
		}
	}

	/**
	 * 异步添加购物车
	 */
	public function ajaxAddCart(){
		if (IS_AJAX){
			$data = I('post.data');
//			dd($data);
			//根据商品id在商品表中获得商品名称以及价格
			$goodsData = (new GoodsModel())->where("gid={$data['gid']}")->field('gname,shopprice')->find();
//			dd($goodsData);
			$data = [
//				键名不能随意添加 必须用Cart类给定的键名
			    'id'              =>  	    $data['gid'],// 商品 ID
				'num'              =>  	    $data['num'],// 商品数量
				'options'          =>  	    $data['options'],// 其他参数如价格、颜色、可以为数组或字符串
				'name'            =>  	    $goodsData['gname'],// 商品名称
				'price'        =>  	    $goodsData['shopprice'],// 商品价格
			];
//			dd($data);
//			Cart类是从hd框架中弄过来的 放在ThinkPHP\Library\Org\Util\Cart中
			(new Cart())->add($data);exit;
		}

	}

}